package com.dtagri.fjwlw.util;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build;

import com.dtagri.fjwlw.AppContext;
import com.dtagri.fjwlw.base.TGson;

/**
 * @author wxjn
 * 
 */
public class TPreferences {
	private static final String PREF_NAME = "creativelocker.pref";

	private static boolean sIsAtLeastGB;

	static {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
			sIsAtLeastGB = true;
		}
	}

	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
	private static void apply(SharedPreferences.Editor editor) {
		if (sIsAtLeastGB) {
			editor.apply();
		} else {
			editor.commit();
		}
	}

	public static void set(String key, boolean value) {
		Editor editor = getPreferences().edit();
		editor.putBoolean(key, value);
		apply(editor);
	}

	public static void set(String key, String value) {
		Editor editor = getPreferences().edit();
		editor.putString(key, value);
		apply(editor);
	}

	public static void set(String key, int value) {
		Editor editor = getPreferences().edit();
		editor.putInt(key, value);
		apply(editor);
	}

	public static boolean get(String key, boolean defValue) {
		return getPreferences().getBoolean(key, defValue);
	}

	public static String get(String key, String defValue) {
		return getPreferences().getString(key, defValue);
	}

	public static int get(String key, int defValue) {
		return getPreferences().getInt(key, defValue);
	}

	public static long get(String key, long defValue) {
		return getPreferences().getLong(key, defValue);
	}

	public static float get(String key, float defValue) {
		return getPreferences().getFloat(key, defValue);
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public static SharedPreferences getPreferences() {
		SharedPreferences pre = AppContext.context().getSharedPreferences(
				PREF_NAME, Context.MODE_MULTI_PROCESS);
		return pre;
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private static SharedPreferences getPreferences(String prefName) {
		return AppContext.context().getSharedPreferences(prefName,
				Context.MODE_MULTI_PROCESS);
	}
	
	public static <T> void set(String key, T t) {
		String json = TGson.gson.toJson(t);
		set(key, json);
	}

	public static <T> T get(String key, Class<T> t) {
		String string = get(key, "{}");
		return TGson.gson.fromJson(string, t);
	}
}
